//文档地址 http://fex.baidu.com/ueditor/#start-config
layui.define(function(exports){
    
    
    class richtext{
        constructor(id){
            this.$id=id;
            this.isEdit=true;
            window.UEDITOR_HOME_URL= __public__ +"/lib/ueditor/";
            if(window.UE){
                this.onScriptLoad();
            }else{
                this.addLike();
                this.addScript();
            }
        }
        
        addLike(){
            var link = document.createElement('link');
            link.rel = 'stylesheet';
            link.media = 'all';
            link.href=window.UEDITOR_HOME_URL+"/themes/iframe.css";
            document.getElementsByTagName('head')[0].appendChild(link);
        }
        
        addScript(url,isAll){
            var $th=this;
            var node = document.createElement('script');
            node.async = false;
            node.charset = 'utf-8';
            node.src=url  || window.UEDITOR_HOME_URL+"/ueditor.config.js";
            document.getElementsByTagName('head')[0].appendChild(node);
            if(node.attachEvent && !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0)){
                node.attachEvent('onreadystatechange', function(e){
                    if(isAll){
                        $th.onScriptLoad(e);
                    }else{
                        $th.addScript(+window.UEDITOR_HOME_URL+"/ueditor.all.min.js",true);
                    }
                });
              } else {
                node.addEventListener('load', function(e){
                    if(isAll){
                        $th.onScriptLoad(e);
                    }else{
                        $th.addScript( window.UEDITOR_HOME_URL+"/ueditor.all.js",true);
                    }
                }, false);
            }
        }
        
        onScriptLoad(){
            var $th=this;
            var toolbars = [[
                'source', //源代码
                '|',
                'undo', //撤销
                'redo', //重做
                '|',
                'bold', //加粗
                'italic', //斜体
                'underline', //下划线
                'horizontal', //分隔线
                'blockquote',
                '|',
                'inserttable', //插入表格
                '|',
                'link', //超链接
                '|',
                'justifyleft', //居左对齐
                'justifycenter', //居中对齐
                'lineheight', //行间距
                "fontfamily",//字段样式
                'forecolor', //字体颜色
                'insertorderedlist', //有序列表
                'insertunorderedlist', //无序列表
                'edittip ', //编辑提示
                '|',
                'paragraph', //段落格式
                'fontsize', //字号
                'customstyle', //自定义标题
                '|',
                'xw_upload',
//              'simpleupload',
                'insertimage', //多图上传
                '|',
                'removeformat', //清除格式
                '|',
                'insertcode', //代码语言
                "preview",
                'template', //模板
                'autotypeset', //自动排版
            ]];
           	this.craftsmanspecial();
            this.ue = UE.getEditor(this.$id, {
                toolbars: toolbars, //显示的导航
                enableAutoSave: false, //启用自动保存
                saveInterval:1000000000, //自动保存间隔时间，单位ms
                fullscreen:false,//全屏
                wordCount:false,//是否开启字数统计
                elementPathEnabled:false,//是否启用元素路径
                maxUndoCount:100,//可以最多回退的次数
                focus:true,//是否让编辑器获得焦点true或false
                scaleEnabled:true,
                insertcode:{'css':'CSS','html':'HTML','js':'JS','php':'PHP','sql':'SQL','xml':'XML'},
                insertorderedlist:{"decimal":"1,2,3","lower-alpha":"a,b,c"},
                insertunorderedlist: { 'circle' : '○ 小圆圈','disc' : '● 小圆点','square' : '■ 小方块'},
                fontfamily:[
                    {label:'',name:'arial',val:'arial, helvetica,sans-serif'},
                    {label:'',name:'songti',val:'宋体,SimSun'},
                    {label:'',name:'kaiti',val:'楷体,楷体_GB2312, SimKai'},
                    {label:'',name:'yahei',val:'微软雅黑,Microsoft YaHei'},
                    {label:'',name:'heiti',val:'黑体, SimHei'},
                    {label:'',name:'lishu',val:'隶书, SimLi'},
                ]
            });
           
            //加载完成
            this.ue.ready(function() {   
            	if(window.__webConfig__ && __webConfig__.editor.imageUrlPrefix ){
            		$th.ue.options.imageUrlPrefix = __webConfig__.editor.imageUrlPrefix;
            	}
                if($th._loadSuccess){
                    $th._loadSuccess();
                }
                if($th.isEdit==false){
                    $th.ue.setDisabled();
                }
            });
            
            this.ue.addListener( 'contentChange', function( editor ) {
                if($th.successCallback){
                    $th.successCallback($th.ue.getContent());
                }
            });
            
        }
        
         /**
		 * 插入专题
		 * @command craftsmanspecial
		 * @method execCommand
		 * @param { String } cmd 命令字符串
		 * @example
		 * ```javascript
		 * editor.execCommand('craftsmanspecial');
		 * ```
		 */
        craftsmanspecial(){
			UE.commands['xw_upload'] = {
			    execCommand : function() {
			        var me = this;
    				$.openWin('/system/gallery/index?id=1', '上传', ['820px', '500px']);
    				window.galleryUploadsCallback = function(data){
    					$.map(data,function(o){ 
    						me.execCommand('inserthtml',`
			            		<p><img src="${ __root__+o.src }" _src="${ __root__+o.src }"></p>
			            	`,true)
    					});
    				}
			    },
			    queryCommandState : function() {
			        return false;
			    }
			}
        }
        
        
        //不可编辑
        setDisabled(){
            this.isEdit=false;
            this.ue.setDisabled();
        }
        
        //可编辑
        setEnabled(){
            this.isEdit=true;
            this.ue.setEnabled();
        }
        
        //内容改变
        contentChange(successCallback){
            if(successCallback){
                this.successCallback=successCallback;
            }
        }
        
        //加载成功
        loadSuccess(successCallback){
            if(successCallback){
                this._loadSuccess=successCallback;
            }
        }
        
    }
    
  exports('richtext',{ init:function(id,opt,xml){ return new richtext(id,opt,xml); } });
});